package org.comparator4j.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;

import org.comparator4j.CompareException;

public class ReflectUtil {
	public static Object invoke(final Method method, final Object instance,
			final Object... args) throws CompareException {
		try {
			return AccessController.doPrivileged(new PrivilegedAction<Object>() {
				public Object run() {
					if (!method.isAccessible()) {
						method.setAccessible(true);
					}
					try {
						return method.invoke(instance, args);
					} catch (IllegalArgumentException e) {
						throw new RuntimeException(e);
					} catch (IllegalAccessException e) {
						throw new RuntimeException(e);
					} catch (InvocationTargetException e) {
						throw new RuntimeException(e);
					}

				}
			});
		} catch (RuntimeException e) {
			if (e.getCause() instanceof IllegalArgumentException) {
				throw new CompareException(e);
			} else if (e.getCause() instanceof IllegalAccessException) {
				throw new CompareException(e);
			} else if (e.getCause() instanceof InvocationTargetException) {
				throw new CompareException(e);
			} else {
				throw e;
			}
		}
	}
}
